package com.bc.commonentity.log;

import com.dianping.cat.message.Transaction;
import com.dianping.cat.message.internal.AbstractMessage;

import java.util.HashMap;
import java.util.Map;

/**
 * 异步调用service和dao层时，用于存储当前线程范围内的变量
 * @date 20160627
 * @author zhaohailong
 *
 */
public class AsynLogDetailHolder {
    /**
     * 线程threadlocal
     */
    private static ThreadLocal<Map<String,Object>> threadLocalMap=new ThreadLocal<>();
    public static <T> T getValueFromThreadLocal(String key){
        if(key==null||key.trim().isEmpty()){
          return null;
        }
        Map<String,Object> map=threadLocalMap.get();
        if(map==null||!map.containsKey(key)){
            return null;
        }
        return (T)map.get(key);
    }
    public static void setValue2ThreadLocal(String key,Object value){
        if(key==null||key.trim().isEmpty()||value==null){
            return;
        }
        Map<String,Object> map=threadLocalMap.get();
        if(map==null){
            map=new HashMap<>();
            threadLocalMap.set(map);
        }
        map.put(key,value);
    }
    public static void clearThreadLocal(boolean isCheck) {
        Map<String,Object> map=threadLocalMap.get();
        if(map!=null&&map.size()>0){
            if(isCheck&&
                    map.containsKey("catTransaction")&&
                    map.get("catTransaction")!=null){
                Transaction t=(Transaction)map.get("catTransaction");
                if(t instanceof AbstractMessage){
                    ErrorEmail.sendErrorMail(t.getName()+"clearThreadLocal时出错",null);
                }
            }
            map.clear();
        }
    }
}